<template>
  <div>
    <!-- 上传区域 -->
    <el-upload 
      action="#"
      v-show="showUpload" 
      ref="upload" 
      :file-list="fileList" 
      list-type="picture-card" 
      :before-upload="beforeUpload" 
      :on-preview="handlePictureCardPreview" 
      :on-remove="handleRemove" 
      :on-change="handleFileChange"
      :limit="1" 
      :auto-upload="false"
      :show-file-list="false">
      <i class="el-icon-plus"></i>
    </el-upload>

    <!-- 图片预览区域 -->
    <div v-if="localImageUrl && !showUpload" class="image-preview">
      <img :src="localImageUrl" class="preview-image">
      <div class="image-actions">
        <i class="el-icon-zoom-in" @click="previewImage"></i>
        <i class="el-icon-delete" @click="removeImage"></i>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ImageSelector',

  props: {
    imageUrl: String // 父组件传入的图片地址
  },

  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      showUpload: true,
      localImageUrl: '', // 本地预览URL
      selectedFile: null  // 选中的文件对象
    };
  },

  watch: {
    imageUrl: {
      immediate: true,
      handler(newVal) {
        if (newVal && newVal !== this.localImageUrl) {
          this.localImageUrl = newVal;
          this.showUpload = false;
        } else if (!newVal) {
          this.localImageUrl = '';
          this.showUpload = true;
        }
      }
    }
  },

  methods: {
    // 文件选择变化处理
    handleFileChange(file, fileList) {
      console.log('文件选择变化处理', file, fileList);
      if (fileList.length > 0) {
        // 生成预览URL
        const previewUrl = URL.createObjectURL(file.raw);
        this.localImageUrl = previewUrl;
        this.selectedFile = file.raw;
        this.showUpload = false;
        
        // 向父组件传递选中的文件
        this.$emit('file-selected', file.raw);
      }
    },

    // 预览图片
    previewImage() {
      this.dialogImageUrl = this.localImageUrl;
      this.dialogVisible = true;
    },

    // 删除图片
    removeImage() {
      this.clearSelection();
      this.$emit('image-removed');
    },

    // 处理移除操作
    handleRemove() {
      this.clearSelection();
      this.$emit('image-removed');
    },

    // 清理选择
    clearSelection() {
      // 释放URL对象
      if (this.localImageUrl.startsWith('blob:')) {
        URL.revokeObjectURL(this.localImageUrl);
      }
      
      // 重置状态
      this.localImageUrl = '';
      this.selectedFile = null;
      this.showUpload = true;
      this.fileList = [];
      
      // 清除上传组件的文件列表
      this.$refs.upload?.clearFiles();
    },

    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 上传前校验
    beforeUpload(file) {
      const validTypes = ['image/png', 'image/jpeg', 'image/gif'];
      const maxSizeMB = 5;
      
      if (!validTypes.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG/PNG/GIF 格式!');
        this.clearSelection();
        return false;
      }
      
      if (file.size / 1024 / 1024 > maxSizeMB) {
        this.$message.error(`上传图片大小不能超过 ${maxSizeMB}MB!`);
        this.clearSelection();
        return false;
      }
      
      return true;
    }
  },

  beforeDestroy() {
    // 组件销毁前释放URL对象
    if (this.localImageUrl.startsWith('blob:')) {
      URL.revokeObjectURL(this.localImageUrl);
    }
  }
};
</script>

<style lang="scss" scoped>
.image-preview {
  width: 148px;
  height: 148px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  position: relative;
  overflow: hidden;

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .image-actions {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: all 0.3s;
    display: flex;
    justify-content: center;
    align-items: center;

    i {
      color: #fff;
      font-size: 20px;
      cursor: pointer;
      margin: 0 10px;
    }
  }

  &:hover .image-actions {
    opacity: 1;
  }
}
</style>